package org.vsaulyak.springrssagregator.bean;

import java.util.List;
import java.util.ArrayList;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import org.vsaulyak.springrssagregator.entity.Chanel;
import org.vsaulyak.springrssagregator.bean.ChanelParser;
import org.vsaulyak.springrssagregator.bean.RssChanelParser;
import org.vsaulyak.springrssagregator.dao.ChanelDao;
import org.vsaulyak.springrssagregator.exception.ChanelParsingException;
import org.vsaulyak.springrssagregator.exception.AppropriateParserNotFoundException;

@Component
public class ChanelHandler 
{
    @Inject
    protected ChanelDao chanelDao;
    private List<ChanelParser> handlers;
    
    public ChanelHandler()
    {
        //TODO move list to configuration
        handlers = new ArrayList<ChanelParser>();
        handlers.add(new RssChanelParser());
    }
    
    public void parseItems(Chanel chanel) throws AppropriateParserNotFoundException
    {
        for (ChanelParser handler : handlers)
        {
            try
            {
                handler.parseItems(chanel);
                chanelDao.persistChanel(chanel);
                return;
            }
            catch (ChanelParsingException e)
            {
                //TODO logging
            }
            throw new AppropriateParserNotFoundException();
        }
    }
    
    public List<Chanel> getChanels()
    {
        return chanelDao.getChanels();
    }
}
